package bank;

public class _67AddBinary {
    public static String addBinary(String a, String b) {
        //  二进制加法
        //  1 + 1 = 0 ; 1 + 0 = 1 ; 0 + 0 = 0;
        StringBuilder res = new StringBuilder();
        int aLen = a.length(),bLen = b.length();
        int ad = 0;
        for (int i = 0;i < Math.min(aLen,bLen);i++){
            //  遍历字符串a和b
            char nowChar = add(a.charAt(aLen-1-i),b.charAt(bLen-1-i),ad);
            res.insert(0,nowChar);
            //  判断进位
            if (canAdv(a.charAt(aLen-1-i),b.charAt(bLen-1-i),ad)){
                ad = 1;
            }else {
                ad = 0;
            }
        }
        //  执行到此处，有可能还需要添加，也有可能不用
        if (aLen == bLen && ad == 1){
            return res.insert(0,1).toString();
        }
        String remain = aLen > bLen ? a : b;
        for (int i = Math.abs(aLen - bLen) - 1;i >= 0;i--){
            char noChar = add(remain.charAt(i),'0',ad);
            res.insert(0,noChar);
            if (canAdv(remain.charAt(i),'0',ad)){
                ad = 1;
            }else {
                ad = 0;
            }
        }
        if (ad == 1){
            res.insert(0,'1');
        }
        return res.toString();
    }

    private static boolean canAdv(char charAta, char charAtb, int ad) {
        int count1 = 0;
        if (charAta == '1'){
            count1++;
        }
        if (charAtb == '1'){
            count1++;
        }
        if (ad == 1){
            count1++;
        }
        return count1 >= 2;
    }

    private static char add(char charAta, char charAtb, int ad) {
        int a = charAta - '0',b = charAtb - '0';
        int res = a ^ b ^ ad;
        return Integer.toString(res).charAt(0);
    }
}
